import {
    Card,
    Space,
    Button,
    Form,
    Input,
    Table,
    Spin,
    notification,
} from 'antd'
import { useRef, useState, useEffect } from 'react'
import CommonDialog from '@/components/commonDialog'
import FormConfig from './components/formConfig'
import { getColumns } from './components/tableColumns'
import {
    getUserlistApi,
    addUserApi,
    deleteUserApi,
    editUserApi,
} from '@/api/tom'
import { getAllRuleListApi } from './components/api'
import React from 'react'

export default function ComputedValue() {
    const [form] = Form.useForm()
    const formRef = useRef<any>(null)
    const [dialogOpen, setDialogOpen] = useState(false)
    const [confirmLoading, setConfirmLoading] = useState(false)
    const [title, setTitle] = useState('新增用户')
    const [dataSource, setDataSource] = useState([])
    const [total, setTotal] = useState(0)
    const [loading, setLoading] = React.useState<boolean>(false)
    const [roleList, setRoleList] = useState([])
    const [tableParams, setTableParams] = useState({
        pagination: {
            current: 1,
            pageSize: 10,
        },
    })
    function fetchData(values = {}) {
        const pageData = {
            page: tableParams.pagination?.current,
            pageSize: tableParams.pagination?.pageSize,
            ...values,
        }
        setLoading(true)
        getUserlistApi(pageData)
            .then((res: any) => {
                setDataSource(res.data.list)
                setTotal(res.data.total)
            })
            .finally(() => {
                setLoading(false)
            })
    }
    function fetchRoleList() {
        getAllRuleListApi().then((res) => {
            setRoleList(
                res.data.map((item: any) => ({
                    label: item.name,
                    value: item.id,
                }))
            )
        })
    }
    useEffect(() => {
        fetchData()
        // 获取角色列表
        fetchRoleList()
    }, [tableParams])

    // 新增操作，打开弹窗并设置内容
    const handleAdd = () => {
        // setDialogContent(`你正在编辑：${name}`)
        setDialogOpen(true)
    }
    // 编辑操作，打开弹窗并设置内容
    const handleEdit = (record: any) => () => {
        setTitle('编辑用户')
        setDialogOpen(true)
        // 等待弹窗打开后，再设置表单数据
        setTimeout(() => {
            formRef.current?.setFieldsValue(record)
        }, 0)
    }
    // 删除操作
    const handleDelete = (key: React.Key) => {
        // 这里可以调用删除接口，删除成功后重新获取数据
        deleteUserApi({ id: key }).then((res) => {
            const config = {
                message: '',
                description: res.message,
                duration: 2,
            }
            notification.success(config)
            fetchData()
        })
    }
    // 弹窗确定按钮，触发表单校验
    const handleDialogOk = async () => {
        if (formRef.current) {
            setConfirmLoading(true)
            try {
                // 获取表单数据
                const values = await formRef.current.submit()
                console.log('表单数据：', values)
                // 这里可以调用新增接口
                if (title === '新增用户') {
                    addUserApi(values)
                        .then((res) => {
                            fetchData()
                            // 校验通过，关闭弹窗
                            setDialogOpen(false)
                            // 重置表单
                            formRef.current?.reset()
                            setConfirmLoading(false)
                        })
                        .finally(() => {
                            setConfirmLoading(false)
                        })
                } else {
                    // 编辑接口
                    editUserApi(values)
                        .then((res) => {
                            fetchData()
                            // 校验通过，关闭弹窗
                            setDialogOpen(false)
                            // 重置表单
                            formRef.current?.reset()
                            setConfirmLoading(false)
                        })
                        .finally(() => {
                            setConfirmLoading(false)
                        })
                }
            } catch (e) {
                setDialogOpen(false)
                setConfirmLoading(false)
            }
        }
    }

    const handleDialogCancel = () => {
        // 重置表单
        formRef.current?.reset()
        setDialogOpen(false)
    }
    const handleQuery = () => {
        // 获取表单值
        const values = form.getFieldsValue()
        // 这里可以根据实际情况进行数据请求
        fetchData(values)
    }
    const resetForm = () => {
        form.resetFields()
        fetchData()
    }
    return (
        <>
            <Spin spinning={loading}>
                <Space
                    direction="vertical"
                    style={{ width: '100%' }}
                    size="middle"
                >
                    <Card>
                        <Form layout="inline" form={form} initialValues={{}}>
                            <Form.Item label="姓名：" name="name">
                                <Input placeholder="" />
                            </Form.Item>
                            <Form.Item>
                                <Space>
                                    <Button
                                        type="primary"
                                        onClick={handleQuery}
                                    >
                                        查询
                                    </Button>
                                    <Button onClick={resetForm}>重置</Button>
                                </Space>
                            </Form.Item>
                        </Form>
                    </Card>
                    <Space align="center">
                        <Button type="primary" onClick={() => handleAdd('')}>
                            新建
                        </Button>
                    </Space>
                    <Table
                        bordered
                        columns={getColumns(handleDelete, handleEdit)}
                        dataSource={dataSource}
                        pagination={{
                            current: tableParams.pagination?.current,
                            pageSize: tableParams.pagination?.pageSize,
                            total, // 确保有 total
                            showSizeChanger: true,
                            showQuickJumper: true,
                            showTotal: () => `共 ${total} 条`,
                            onChange: (page, pageSize) => {
                                setTableParams({
                                    pagination: {
                                        ...tableParams.pagination,
                                        current: page,
                                        pageSize,
                                    },
                                })
                                // 这里可以触发数据请求
                            },
                        }}
                    />
                </Space>
                <CommonDialog
                    open={dialogOpen}
                    title={title}
                    width={600}
                    confirmLoading={confirmLoading}
                    onOk={handleDialogOk}
                    onCancel={handleDialogCancel}
                >
                    <FormConfig ref={formRef} roleList={roleList} />
                </CommonDialog>
            </Spin>
        </>
    )
}
